<template>
  <div class="layout-padding">
    <!-- 设备列表清单 -->
    <el-card shadow="hover" class="layout-padding-auto">
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="在用设备" name="1">
          <el-row>
            <el-col :span="16">
              <el-input
                style="width: 30%; margin: 5px 0"
                v-model="search.keyword"
                placeholder="可输入设备名称、编号、型号搜索"
              />
              <span style="margin: 0 5px 0 10px">设备类型</span>
              <a-tree-select
                v-model:value="deviceTypes"
                style="
                  margin: 5px 0;
                  width: 300px;
                  font-size: var(--el-font-size-base);
                "
                show-search
                placeholder="请选择"
                allow-clear
                multiple
                :maxTagCount="4"
                tree-default-expand-all
                :tree-data="cascaderData"
                :fieldNames="cascaderPropsAut"
                @change="cascaderChange"
              >
                <template #title="{ value: val, configValue }">
                  {{ configValue }}
                </template>
              </a-tree-select>
              <span style="margin: 0 5px 0 10px">设备状态</span>
              <el-select
                style="margin: 5px 0"
                v-model="search.deviceStatus"
                class="m-2"
                placeholder="请选择"
              >
                <el-option label="全部" value="" />
                <el-option label="使用中" value="1" />
                <el-option label="维修中" value="2" />
                <el-option label="维保中" value="3" />
                <el-option label="点检中" value="4" />
              </el-select>
              <el-button
                style="margin-left: 12px"
                type="primary"
                @click="searchFor"
                >搜索</el-button
              >
              <el-button type="primary" plain @click="resetFor">重置</el-button>
            </el-col>
            <el-col :span="8" style="text-align: right">
              <el-button
                class="btn"
                type="primary"
                @click="addEquipment"
                v-if="buttonDisplayOrNot(buttonCodes, 'deviceAddBtn')"
                >新增设备</el-button
              >
              <el-button
                class="btn"
                type="primary"
                plain
                @click="batchImportDevice"
                v-if="
                  buttonDisplayOrNot(buttonCodes, 'deviceBatchImportDeviceBtn')
                "
                >批量导入设备</el-button
              >
              <el-button
                class="btn"
                type="primary"
                plain
                @click="debounce(importTemplateDownload, 1000)"
                v-if="
                  buttonDisplayOrNot(buttonCodes, 'deviceImportTemplateBtn')
                "
                >导入模板下载</el-button
              >
              <el-button
                class="btn"
                type="primary"
                plain
                @click="debounce(exportQRCode, 1000)"
                v-if="buttonDisplayOrNot(buttonCodes, 'deviceExportQRCodeBtn')"
                >导出二维码</el-button
              >
            </el-col>
          </el-row>
          <Table
            ref="tableRef"
            v-bind="state.tableData"
            class="table-demo"
            @pageChange="onTablePageChange"
            @listenClick="listenClick"
            @dataList="dataList"
          >
            <template #default="{ slotData, slotColumn }">
              <div v-if="slotColumn.key === 'deviceStatus'">
                {{
                  slotData.deviceStatus == 1
                    ? '使用中'
                    : slotData.deviceStatus == 2
                    ? '维修中'
                    : slotData.deviceStatus == 3
                    ? '维保中'
                    : slotData.deviceStatus == 4
                    ? '点检中'
                    : ''
                }}
              </div>
              <div v-if="slotColumn.key === 'QRCode'">
                <el-button
                  type="primary"
                  text="primary"
                  link
                  v-if="buttonDisplayOrNot(buttonCodes, 'deviceViewQRCodeBtn')"
                  @click="chakan(slotData.qrCodePicture, slotData.deviceName)"
                  >查看</el-button
                >
                <el-button
                  type="primary"
                  text="primary"
                  link
                  v-if="
                    buttonDisplayOrNot(buttonCodes, 'deviceExportOneQRCodeBtn')
                  "
                  @click="daochu(slotData)"
                  >导出</el-button
                >
              </div>
            </template>
          </Table>
          <EquipmentDialog
            :dialogForm="dialogForm"
            :dialogVisible="dialogVisible"
            @cancel="cancel"
            @submit="submit"
          >
          </EquipmentDialog>
        </el-tab-pane>
        <el-tab-pane label="停用台账" name="0">
          <el-row>
            <el-col :span="18">
              <el-input
                style="width: 30%"
                v-model="search2.keyword"
                placeholder="可输入设备名称、编号、型号搜索"
              />
              <span style="margin-left: 10px">设备类型</span>
              <a-tree-select
                v-model:value="deviceTypes2"
                style="
                  margin: 5px 0;
                  width: 300px;
                  font-size: var(--el-font-size-base);
                "
                show-search
                placeholder="请选择"
                allow-clear
                multiple
                :maxTagCount="4"
                tree-default-expand-all
                :tree-data="cascaderData2"
                :fieldNames="cascaderPropsAut"
                @change="cascaderChange2"
              >
                <template #title="{ value: val, configValue }">
                  {{ configValue }}
                </template>
              </a-tree-select>
              <el-button
                style="margin-left: 10px"
                type="primary"
                @click="searchFor2"
                >搜索</el-button
              >
              <el-button type="primary" plain @click="resetFor2"
                >重置</el-button
              >
            </el-col>
            <el-col :span="6" style="text-align: right"> </el-col>
          </el-row>
          <Table
            ref="tableRef"
            v-bind="state.tableData2"
            class="table-demo"
            @pageChange="onTablePageChange2"
            @listenClick="listenClick"
          >
            <template #default="{ slotData, slotColumn }">
              <div v-if="slotColumn.key === 'deviceStatus'">已停用</div>
              <div v-if="slotColumn.key === 'QRCode'">
                <el-button
                  type="primary"
                  text="primary"
                  link
                  @click="chakan(slotData.qrCodePicture, slotData.deviceName)"
                  >查看</el-button
                >
                <el-button
                  type="primary"
                  text="primary"
                  link
                  @click="daochu(slotData)"
                  >导出</el-button
                >
              </div>
            </template>
          </Table>
        </el-tab-pane>
      </el-tabs>
      <EnlargePicture
        :pictureDialog="pictureDialog"
        :pictureForm="pictureForm"
        @closePicture="closePicture"
      >
      </EnlargePicture>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, reactive, onMounted, defineAsyncComponent } from 'vue'
import {
  ElMessage,
  ElMessageBox,
  TabsPaneContext,
  ElNotification
} from 'element-plus'
import routes from '/@/router'
import {
  deleteDeviceApi,
  downloadMouldApi,
  importDeviceApi,
  updateStopFlagApi,
  deviceQrCodeBatchReportApi,
  deviceQrCodeReportApi
} from '/@/api/assets'
import { useRoute } from 'vue-router'
import { Session } from '/@/utils/storage'
import {
  bindFileUrlApi,
  dictionaryList,
  getButtonListByRoleApi
} from '/@/api/publicApi'
import { buttonDisplayOrNot } from '../../utils/buttonBoolean'
import { debounce } from '/@/utils/loading'
const menu = Session.get('menu')
const EquipmentDialog = defineAsyncComponent(
  () => import('./components/EquipmentDialog.vue')
)
const Table = defineAsyncComponent(
  () => import('/@/components/table/index.vue')
)
const EnlargePicture = defineAsyncComponent(
  () => import('./components/EnlargePicture.vue')
)
const route = useRoute()
const dialogVisible = ref<boolean>(false) //弹窗是否出现
const dialogForm = {
  width: '45%',
  title: '',
  id: ''
}

const buttonCodes = ref<any>([])
const activeName = ref(route.query.active ? route.query.active : '1')
const status = ref(route.query.status ? route.query.status : '') as any

// 定义变量内容
const tableRef = ref<RefType>()
const state = reactive<TableDemoState>({
  tableData: {
    flash: false, // 刷新表格
    // 表头内容（必传，注意格式）
    header: [
      { key: 'deviceNum', colWidth: '160', title: '设备编号', type: 'text' },
      { key: 'deviceName', colWidth: '160', title: '设备名称', type: 'text' },
      {
        key: 'deviceTypeName',
        colWidth: '160',
        title: '设备类型',
        type: 'text'
      },
      { key: 'modelName', colWidth: '160', title: '设备型号', type: 'text' },
      { key: 'deptName', colWidth: '160', title: '所在部门', type: 'text' },
      { key: 'deviceStatus', colWidth: '160', title: '设备状态', type: 'slot' },
      { key: 'QRCode', colWidth: '160', title: '设备二维码', type: 'slot' }
    ],
    columnBtn: [
      {
        name: 'deviceDetail',
        text: '设备详情',
        type: 'primary',
        btns: buttonCodes.value,
        btnCode: 'deviceDetailBtn'
      },
      {
        name: 'deviceEdit',
        text: '编辑',
        color: '#1962E0',
        btns: buttonCodes.value,
        btnCode: 'deviceEditBtn'
      },
      {
        name: 'deviceStop',
        text: '停用',
        type: 'warning',
        btns: buttonCodes.value,
        btnCode: 'deviceStopBtn'
      },
      {
        name: 'allPersonal',
        text: '全部履历',
        color: '#00BAAD',
        btns: buttonCodes.value,
        btnCode: 'deviceAllResumeBtn'
      },
      {
        name: 'deviceDel',
        text: '删除',
        type: 'danger',
        btns: buttonCodes.value,
        btnCode: 'deviceDeleteBtn'
      }
    ],
    // 配置项（必传）
    config: {
      listApi: '/device/mobile/deviceInfo/deviceListByPage',
      listHttp: 'post',
      total: 0, // 列表总数
      loading: true, // loading 加载
      noPage: false, // 是否分页
      isSerialNo: false, // 是否显示表格序号
      isSelection: true, // 是否显示表格多选
      isOperate: true, // 是否显示表格操作栏
      isExtend: false, // 是否可以扩展
      operateWidth: '450', //操作栏宽度
      fixed: 'right' //操作栏固定
    },
    // 搜索参数
    param: {
      stopFlag: 0 // 必传参数，分页的不要传
    }
  },
  tableData2: {
    flash: false, // 刷新表格
    // 表头内容（必传，注意格式）
    header: [
      { key: 'deviceNum', colWidth: '160', title: '设备编号', type: 'text' },
      { key: 'deviceName', colWidth: '160', title: '设备名称', type: 'text' },
      {
        key: 'deviceTypeName',
        colWidth: '160',
        title: '设备类型',
        type: 'text'
      },
      { key: 'modelName', colWidth: '160', title: '设备型号', type: 'text' },
      { key: 'deptName', colWidth: '160', title: '所在部门', type: 'text' },
      { key: 'deviceStatus', colWidth: '160', title: '设备状态', type: 'slot' },
      { key: 'QRCode', colWidth: '160', title: '设备二维码', type: 'slot' }
    ],
    columnBtn: [
      {
        name: 'deviceDetail',
        text: '设备详情',
        hide(row: any): boolean {
          return true
        },
        type: 'primary',
        btns: buttonCodes.value,
        btnCode: 'deviceShopDetailBtn'
      },
      {
        name: 'deviceFiring',
        text: '启用',
        hide(row: any): boolean {
          return true
        },
        type: 'primary',
        btns: buttonCodes.value,
        btnCode: 'deviceShopEnableBtn'
      },
      {
        name: 'allPersonal',
        text: '全部履历',
        hide(row: any): boolean {
          return true
        },
        type: 'primary',
        btns: buttonCodes.value,
        btnCode: 'deviceShopAllResumeBtn'
      },
      {
        name: 'deviceDel',
        text: '删除',
        hide(row: any): boolean {
          return true
        },
        type: 'danger',
        btns: buttonCodes.value,
        btnCode: 'deviceShopDeleteBtn'
      }
    ],
    // 配置项（必传）
    config: {
      listApi: '/device/mobile/deviceInfo/deviceListByPage',
      listHttp: 'post',
      total: 0, // 列表总数
      loading: true, // loading 加载
      noPage: false, // 是否分页
      isSerialNo: true, // 是否显示表格序号
      isSelection: false, // 是否显示表格多选
      isOperate: true, // 是否显示表格操作栏
      isExtend: false, // 是否可以扩展
      operateWidth: '400', //操作栏宽度
      fixed: 'right' //操作栏固定
    },
    // 搜索参数
    param: {
      stopFlag: 1 // 必传参数，分页的不要传
    }
  }
})

const search = ref({
  keyword: '',
  deviceTypes: [],
  deviceStatus: '',
  stopFlag: 0
})
const search2 = ref({
  keyword: '',
  deviceTypes: [],
  stopFlag: 1
})
const cascaderData = ref([])
const cascaderData2 = ref([])
const cascaderPropsAut = {
  value: 'id',
  label: 'configValue',
  children: 'children'
}
const cascaderProps2 = {
  expandTrigger: 'click' as const,
  value: 'id',
  label: 'configValue',
  emitPath: true,
  multiple: true,
  checkStrictly: true
}
const deviceTypes = ref<any>([])
const deviceTypes2 = ref<any>([])
const cascaderChange = (val: any) => {
  search.value.deviceTypes = val
}
const cascaderChange2 = (val: any) => {
  search2.value.deviceTypes = val
}

const getDeviceType = () => {
  dictionaryList({ configType: 'device_type', keyword: '' }).then((res) => {
    if (res.code == 0) {
      cascaderData.value = res.data
      cascaderData2.value = res.data
    }
  })
}
getDeviceType()

const searchFor = () => {
  state.tableData.param = Object.assign({}, state.tableData.param, {
    ...search.value
  })
  state.tableData.flash = !state.tableData.flash
  daochuObj.value.deviceStatus = search.value.deviceStatus
  daochuObj.value.deviceType = search.value.deviceTypes.join(',')
  daochuObj.value.keyword = search.value.keyword
}

const resetFor = () => {
  search.value.keyword = ''
  search.value.deviceTypes = []
  search.value.deviceStatus = ''
  deviceTypes.value = []
  searchFor()
}
const searchFor2 = () => {
  state.tableData2.param = Object.assign({}, state.tableData2.param, {
    ...search2.value
  })
  state.tableData2.flash = !state.tableData2.flash
}

const resetFor2 = () => {
  search2.value.keyword = ''
  search2.value.deviceTypes = []
  deviceTypes2.value = []
  searchFor2()
}

const daochuObj = ref({
  deviceStatus: '',
  deviceType: '',
  keyword: '',
  deviceIds: <any>[]
})

const list = ref([])
const dataList = (val: any) => {
  list.value = val.records
}

// 分页改变时回调
const onTablePageChange = (page: TableDemoPageType) => {
  state.tableData.param.pageNum = page.pageNum
  state.tableData.param.pageSize = page.pageSize
  searchFor()
}

// 分页改变时回调
const onTablePageChange2 = (page: TableDemoPageType) => {
  state.tableData2.param.pageNum = page.pageNum
  state.tableData2.param.pageSize = page.pageSize
  searchFor2()
}

//打开新增设备窗口
const addEquipment = () => {
  dialogForm.title = '新增设备'
  dialogForm.id = ''
  dialogVisible.value = !dialogVisible.value
}
const deviceEdit = (row: any) => {
  dialogForm.title = '编辑设备'
  dialogForm.id = row.id
  dialogVisible.value = !dialogVisible.value
}
const cancel = () => {
  dialogVisible.value = !dialogVisible.value
}
const submit = () => {
  searchFor()
  dialogVisible.value = !dialogVisible.value
}

const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event)
}

const deviceDetail = (row: any) => {
  if (activeName.value == '0') {
    routes.push({
      name: 'deviceDetail',
      query: {
        id: row.id,
        activeName: '0'
      }
    })
  } else {
    routes.push({
      name: 'deviceDetail',
      query: {
        id: row.id,
        activeName: '1'
      }
    })
  }
}

const allPersonal = (row: any) => {
  if (activeName.value == '0') {
    routes.push({
      name: 'allPersonal',
      query: {
        id: row.id,
        name: row.deviceName,
        activeName: '0'
      }
    })
  } else {
    routes.push({
      name: 'allPersonal',
      query: {
        id: row.id,
        name: row.deviceName,
        activeName: '1'
      }
    })
  }
}

const pictureDialog = ref(false)
const pictureForm = ref({
  val: '',
  type: 0,
  name: ''
})
const chakan = async (qrCodePicture: any, name: any) => {
  let res = await bindFileUrlApi(qrCodePicture)
  if (res.code == 0) {
    pictureForm.value.val = res.data
  }
  pictureForm.value.name = name
  pictureForm.value.type = 1
  pictureDialog.value = !pictureDialog.value
}
const closePicture = () => {
  pictureDialog.value = !pictureDialog.value
}

let timer: any = null
const daochu = (row: any) => {
  timer && clearTimeout(timer)
  timer = setTimeout(() => {
    let params = {
      deviceId: row.id
    }
    deviceQrCodeReportApi(params).then((res: any) => {
      let blob = new Blob([res], {
        type: 'application/png;charset=UTF-8'
      })
      let url = window.URL.createObjectURL(blob)
      const link = document.createElement('a') // 创建a标签
      link.download = row.deviceName + '二维码.png'
      link.href = url
      link.click()
      URL.revokeObjectURL(url) // 释放内存
    })
  }, 1000)
}

let timer2: any = null
const exportQRCode = () => {
  timer2 && clearTimeout(timer2)
  timer2 = setTimeout(() => {
    if (list.value.length == 0) {
      ElMessage.warning('暂无数据可导出')
      loading.value = false
    } else {
      deviceQrCodeBatchReportApi(daochuObj.value).then((res) => {
        if (res.code == 0) {
          ElMessage.success('导出成功,请在下载中心查看')
        }
      })
    }
  }, 1000)
}

const deviceFiring = (row: any) => {
  ElMessageBox.confirm(
    '确定启用该设备？启用后，可以对该设备进行维修、维保、点检操作',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(() => {
      updateStopFlagApi(row.id).then((res) => {
        if (res.code == 0) {
          ElMessage({
            type: 'success',
            message: '已启用'
          })
          searchFor2()
          searchFor()
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消'
      })
    })
}
const deviceStop = (row: any) => {
  ElMessageBox.confirm(
    '确定停用该设备？停用后将无法对该设备进行维修、维保、点检等操作',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(() => {
      updateStopFlagApi(row.id).then((res) => {
        if (res.code == 0) {
          ElMessage({
            type: 'success',
            message: '已停用'
          })
          searchFor()
          searchFor2()
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消'
      })
    })
}

const deviceDel = (row: any) => {
  ElMessageBox.confirm('确定删除该设备？删除后，设备数据将无法恢复', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      deleteDeviceApi(row.id).then((res) => {
        if (res.code == 0) {
          ElMessage({
            type: 'success',
            message: '删除成功'
          })
          searchFor()
          searchFor2()
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消'
      })
    })
}

const loading = ref(false)

const importTemplateDownload = () => {
  downloadMouldApi().then((res: any) => {
    let blob = new Blob([res], {
      type: 'application/vnd.ms-excel;charset=UTF-8'
    })
    let url = window.URL.createObjectURL(blob)
    const link = document.createElement('a') // 创建a标签
    link.download = '设备导入模板.xlsx'
    link.href = url
    link.click()
    URL.revokeObjectURL(url) // 释放内存
  })
}

const batchImportDevice = () => {
  const fileType = ['xls', 'xlsx']
  const inputFile = document.createElement('input') as any
  inputFile.type = 'file'
  inputFile.style.display = 'none'
  document.body.appendChild(inputFile)
  inputFile.click()
  inputFile.addEventListener('change', () => {
    const file = inputFile.files[0]
    var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
    if (!fileType.includes(testmsg)) {
      ElMessage.warning('上传的文件格式只能是excel文档')
      document.body.removeChild(inputFile)
      return false
    }
    //上传接口
    importDeviceApi({ file: file }).then((res) => {
      if (res.code == 0) {
        ElNotification({
          title: '设备导入成功',
          message: '',
          type: 'success'
        })
        searchFor()
      }
    })
  })
}

const onSelectionChange = (selection: any) => {
  daochuObj.value.deviceIds = []
  selection.forEach((element: any) => {
    daochuObj.value.deviceIds.push(element.id)
  })
}

const onSelect = () => {}

//定义方法对象 注意定义的方法 必须在上面已经申明 所以建议objFun申明和 listenClick方法 写在页面最下面
const objFun = {
  addEquipment: addEquipment,
  deviceDetail: deviceDetail,
  allPersonal: allPersonal,
  deviceStop: deviceStop,
  deviceFiring: deviceFiring,
  deviceDel: deviceDel,
  deviceEdit: deviceEdit,
  importTemplateDownload: importTemplateDownload,
  batchImportDevice: batchImportDevice,
  exportQRCode: exportQRCode,
  onSelectionChange: onSelectionChange,
  onSelect: onSelect
}
// 监听子级表格  传过来的方法
const listenClick = (name: string, val: any) => {
  objFun[name](val)
}

// 页面加载时
onMounted(() => {
  menu.forEach(async (element: any) => {
    if (element.menuUrl == '/assets/equipment') {
      let res = await getButtonListByRoleApi({
        terminalType: 1,
        menuPid: element.id
      })
      res.data.forEach((item: any) => {
        buttonCodes.value.push(item.buttonCode)
      })
    }
  })
  if (status.value && status.value != '5') {
    search.value.deviceStatus = status.value
    searchFor()
  } else if (status.value && status.value == '5') {
    activeName.value = '0'
  }
})
</script>
<style lang="scss" scoped>
.btn {
  margin-bottom: 10px;
}
</style>
<style>
.el-button--warning.is-plain {
  --el-button-bg-color: #fdf6ec;
  --el-button-hover-text-color: #e6a23c;
  --el-button-hover-bg-color: #fdf6ec;
}

.el-button--warning.is-plain:hover {
  --el-button-hover-text-color: #fff;
  --el-button-hover-bg-color: #e6a23c;
}

.el-button--danger.is-plain {
  --el-button-bg-color: #fef0f0;
  --el-button-hover-text-color: #f56c6c;
  --el-button-hover-bg-color: #fef0f0;
}

.el-button--danger.is-plain:hover {
  --el-button-hover-text-color: #fff;
  --el-button-hover-bg-color: #f56c6c;
}
</style>
